package com.ganee.agora.view
import android.os.Bundle
import android.text.TextUtils
import android.view.Gravity
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener

import com.ganee.baselib.mvvmlibrary.base.BaseActivity
import com.ganee.agora.R
import com.ganee.agora.adapter.MenuAdapter
import com.ganee.agora.event.PostEvent
import com.ganee.agora.model.MenuEntity
import com.ganee.agora.model.UserInfoEntity
import com.ganee.agora.view.fragment.HomeFragment
import com.ganee.agora.view.fragment.HostEventFragment
import com.ganee.agora.view.fragment.RegistrationsFragment
import com.ganee.agora.view.fragment.YourListFragment
import com.ganee.agora.viewmodel.MainViewModel
import com.ganee.baselib.arouter.Constance
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.toolbar_organization_department.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

//主页
@Route(path = Constance.ACTIVITY_URL_MAIN)
class MainActivity : BaseActivity<MainViewModel>(), View.OnClickListener {


    private val Home = 0
    private var LASTPOSITION = 0

    private val menuList = mutableListOf<MenuEntity>()
    private var manager: FragmentManager? = null
    private val list = mutableListOf<Fragment>()
    override fun getViewModel(): MainViewModel {
        return ViewModelProviders.of(this@MainActivity).get(MainViewModel::class.java)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        ARouter.getInstance().inject(this)
        EventBus.getDefault().register(this)
        initFragment()
        initView()
        initRequestData()
    }

    private fun initView() {
        toolbarRl.setBackgroundResource(R.color.white)
        toolbarEtSearch.visibility = View.GONE
        toolbarSearch.isEnabled = true
        toolbarEtSearch.setOnEditorActionListener(TextView.OnEditorActionListener { v, actionId, event ->
            if ((actionId == 0 || actionId == 3) && event != null) {
                //点击搜索要做的操作
                ARouter.getInstance()
                        .build(Constance.ACTIVITY_URL_SEARCH_FILTER)
                        .withString("inputStr",toolbarEtSearch.text.toString().trim())
                        .navigation(this)
            }
            false
        })
        manager = supportFragmentManager;
        val drawerToggle = ActionBarDrawerToggle(this, drawer_layout, null, R.string.app_name, R.string.app_name)
        drawer_layout.addDrawerListener(drawerToggle)
        drawerToggle.syncState()
        switchFragment(Home)
        menuRecyclerView.setHasFixedSize(false)
        menuRecyclerView.layoutManager = LinearLayoutManager(this)

        toolbarMenu.setOnClickListener(this)
        toolbarSearch.setOnClickListener(this)
        toolbarAdd.setOnClickListener(this)
        rl_top.setOnClickListener {}
        rl_bottom.setOnClickListener{}

        menuList.clear()
        menuList.add(MenuEntity("Deck", R.drawable.deck, "Home"))
        menuList.add(MenuEntity("Sign-ups", R.drawable.sign_ups, "Registrations"))
        menuList.add(MenuEntity("Your events", R.drawable.your_events, "Event"))
        menuList.add(MenuEntity("Bookmarks", R.drawable.bookmarks, "List"))
        menuList.add(MenuEntity("About you", R.drawable.about_you, "Profile"))
        menuList.add(MenuEntity("Settings", R.drawable.settings, "Settings"))
        val menuAdapter = MenuAdapter(menuList)
        menuRecyclerView.adapter = menuAdapter
        menuRecyclerView.addOnItemTouchListener(object : OnItemClickListener() {
            override fun onSimpleItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
                val entity = adapter?.getItem(position) as MenuEntity
                when (entity.type) {
                    "Home" -> {
                        drawer_layout.closeDrawer(Gravity.LEFT)
                        switchFragment(Home)
                    }
                    "Registrations" -> {
                        drawer_layout.closeDrawer(Gravity.LEFT)
                        ARouter.getInstance().build(Constance.ACTIVITY_URL_SIGN_UP).navigation()
                    }
                    "Event" -> {
                        drawer_layout.closeDrawer(Gravity.LEFT)
                        ARouter.getInstance().build(Constance.ACTIVITY_URL_YOUR_EVENT).navigation()
                    }
                    "List" -> {
                        drawer_layout.closeDrawer(Gravity.LEFT)
                        ARouter.getInstance().build(Constance.ACTIVITY_URL_BOOKMARK).navigation()
                    }
                    "Profile" -> {
                        drawer_layout.closeDrawer(Gravity.LEFT)
                        ARouter.getInstance().build(Constance.ACTIVITY_URL_PROFILE).navigation()
                    }
                    "Settings" -> {
                        drawer_layout.closeDrawer(Gravity.LEFT)
                        ARouter.getInstance()
                                .build(Constance.ACTIVITY_URL_SETTINGS)
                                .navigation()
                    }
                }
            }
        })
    }

    //自己创建fragment
    private fun initFragment() {
        list.add(HomeFragment())
    }

    private fun initRequestData() {
        viewModel.getUserInfo()
        viewModel.getUserInfoEntity.observe(this, Observer<UserInfoEntity> {
            if (!TextUtils.isEmpty(it.firstName) && !TextUtils.isEmpty(it.lastName)) {
                menu_tv_username.text = it.firstName + " " + it.lastName
            }
            menu_tv_cash.text = it.packetBalan ?: "0"
            Glide.with(this@MainActivity)
                    .load(it.userPic)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .centerCrop()
                    .dontAnimate()
                    .thumbnail(0.5f)
                    .placeholder(R.drawable.avatar_placeholder)
                    .error(R.drawable.avatar_placeholder)
                    .into(menu_avatar)
        })

    }


    override fun onClick(v: View?) {
        when (v!!.id) {
            R.id.toolbarMenu -> {
                drawer_layout.openDrawer(Gravity.LEFT)
            }
            R.id.toolbarSearch -> {
                toolbarRl.setBackgroundResource(R.drawable.bg_main_search)
                toolbarEtSearch.visibility = View.VISIBLE
                toolbarSearch.isEnabled = false
            }
            R.id.toolbarAdd -> {
                ARouter.getInstance().build(Constance.ACTIVITY_URL_POST_EVENT).navigation(this)
            }
        }
    }

    private fun switchFragment(position: Int) {
        val transaction = manager!!.beginTransaction()
        val fragment = list[position]
        if (!fragment.isAdded) {
            transaction.add(R.id.frameLayout, fragment)
        }
        val lastFragment = list[LASTPOSITION]
        transaction.hide(lastFragment)
        transaction.show(fragment)
        transaction.commit()
        LASTPOSITION = position
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun refresh(event: PostEvent) {
        if ("post" == event.type) {
            switchFragment(Home)
        } else if ("profile" == event.type) {
            initRequestData()
        }
    }
}
